package com.example.consumer1;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * <b>TODO . </b>
 *
 * @author yangyl11
 * @version 1.0.0
 * @date 2020/11/9
 * @since JDK 1.8
 */
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class TestController {

	private Logger logger = LoggerFactory.getLogger(TestController.class);
	@Resource
	private RemoteService remoteService;

	@Resource
	private RestTemplate restTemplate;

	@RequestMapping("/test/restTemplate")
	public String testRestTemplate() {

		logger.info("test consumer1");
		return restTemplate.getForObject("http://PROVIDER1/test", String.class);
	}

	@RequestMapping("/test/feignClient")
	public String testFeignClient() {

		logger.info("test consumer1");
		return remoteService.test1("feign");
	}

	@RequestMapping("/test1")
	@HystrixCommand(fallbackMethod = "testFallback")
	public String test1() {

		return restTemplate.getForObject("http://PROVIDER1/test", String.class);
	}

	@RequestMapping("/test2")
	@HystrixCommand
	public String test2() {

		return remoteService.test1("feign");
	}

	@RequestMapping("/test3/{num}")
	@HystrixCommand(
			commandProperties = {
					@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//熔断触发的最小个数/10s 默认值：20
					@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),//失败率达到多少百分比后熔断 默认值：50
					@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000")//熔断多少秒后去尝试请求 默认值：5000
			}
	)
	public String test3(@PathVariable Integer num) {

		int a = 1 / num;
		return "结果为：" + a;
	}

	@RequestMapping("/test4/{num}")
	@HystrixCommand
	public String test4(@PathVariable Integer num) {

		int a = 1 / num;
		return "结果为：" + a;
	}

	public String testFallback() {

		return "系统开小差了o(╥﹏╥)o";
	}

	public String defaultFallback() {

		return "system error o(╥﹏╥)o";
	}
}
